/**
 * @desc
 *
 * 页面相关JS与CSS信息..
 *
 * 注:
 * 首页只有一条有效的,所以切换首页时要修改这里的内容..
 *
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    2017/6/14
 **/

import PageResourcesModel from '../dao/rn-page/rn-page-resources-model';

interface PageResourcesQueryI {
    systemCode:string,
    platform:string,
    uid:string,

    pageType ?:string,
    pageCode ?:string
}


/**
 * 查询页面的资源信息.
 * @param pageResourcesI
 * @returns {Promise<T>}
 */
export function getPageResources(pageResourcesI:PageResourcesQueryI):Promise<Array<Object>> {

    let queryParams = {
        systemCode: pageResourcesI.systemCode,
        platform: pageResourcesI.platform,
        uid: pageResourcesI.uid
    };

    if(pageResourcesI.pageType ){
        queryParams['pageType'] = pageResourcesI.pageType;
    }


    if(pageResourcesI.pageCode ){
        queryParams['pageCode'] = pageResourcesI.pageCode;
    }

    return new Promise((resolve, reject) => {
        PageResourcesModel.find(queryParams).lean().exec((err,data:any)=>{
            if(err){
                reject(err);
            }else{
                resolve(data);
            }
        });
    });


}

interface PageResourcesSaveI{

    systemCode: string;
    platform: string;
    uid: string;
    pageType ?: string;
    pageCode ?: string;
    url:string;
    version:string;
    resourceType:string;

    pageRelInfo?:Object;
}

/**
 *
 * @param pageResourcesSaveI
 * @returns {Promise<T>}
 */
export function upsertPageResources(pageResourcesSaveI : PageResourcesSaveI) {
    let _target ={
        systemCode:pageResourcesSaveI.systemCode,
        uid:pageResourcesSaveI.uid,
        platform:pageResourcesSaveI.platform,
        pageType:pageResourcesSaveI.pageType,
        pageCode:pageResourcesSaveI.pageCode,
    }

    delete pageResourcesSaveI['_id'];
    delete pageResourcesSaveI['__v'];


    return new Promise((resolve, reject) => {
        PageResourcesModel.update(_target, pageResourcesSaveI, {"upsert": true}).exec(function (err, data) {
            err ? reject(err) : resolve(data);
        });
    });

}